/*
 * @Author:your name
 * @Date:2020-11-08 18:02:34
 * @LastEditTime2020-11-25 23:11:23
 * @LastEditorsPlease set LastEditors
 * @Description:In User Settings Edit
 * @FilePath:\STM32F103_FreeRTOS\User\app\shell\shell_cmd.c
 */ 
#include <stdio.h>
#include <string.h>
#include "shell_cmd.h"
#include "shell_hash.h"
#include "cmsis_armcc.h"

#include "backtrace.h"

static void help(void);
static void hello(void);
static void list_task(void);
static void print_sp(void);
static void reset(void);

static hash_table_t shell_cmd_table;

const shell_cmd_cfg_t g_shell_cmd_cfg[SHELL_CMD_NUM] __attribute__((section(".shell_const"))) = 
{
    {"help"     , help     },
    {"hello"    , hello    },
    {"list_task", list_task},
    {"print_sp" , print_sp },
    {"reset"    , reset    },
};

void shell_cmd_init(void)
{
    uint16_t index = 0;
    hash_init(&shell_cmd_table);
    for(index = 0; index < SHELL_CMD_NUM; index++)
    {
        hash_add(&shell_cmd_table, g_shell_cmd_cfg[index].pCmd, 
            sizeof(g_shell_cmd_cfg[index].pCmd), index);
    }
}

shell_cmd_func shell_cmd_find(char *cmd_name, uint16_t cmd_len)
{
    uint16_t index = 0;
#if SHELL_FIND_HASH
    if(hash_find(&shell_cmd_table, cmd_name, cmd_len, &index))
    {
        return g_shell_cmd_cfg[index].callback;
    }
    else
    {
        return NULL;
    }
#else
    for(index = 0; index < SHELL_CMD_NUM; ++index)
    {   
        if(strncmp(cmd_name, g_shell_cmd_cfg[index].pCmd, cmd_len) == 0)
        {
            return g_shell_cmd_cfg[index].callback;
        }
    }
    return NULL;
#endif
}

boolean shell_cmd_match(char *prefix, uint16_t prefix_len, char **cmd_str)
{
    uint16_t index = 0;
    for(index = 0; index < SHELL_CMD_NUM; ++index)
    {   
        if(strncmp(prefix, g_shell_cmd_cfg[index].pCmd, prefix_len) == 0)
        {
            *cmd_str = g_shell_cmd_cfg[index].pCmd;
            return TRUE;
        }
    }
    return FALSE;
}

static void help(void)
{
    printf("Help command.\r\n");
}

static void hello(void)
{
    printf("Hello command.\r\n");
}

static void list_task(void)
{
    printf("List task command.\r\n");
}

static void print_sp(void)
{
    // backtrace_assert(__get_PSP());
}

static void reset(void)
{
    
}
